package com.fyb.basic.juc.masterWork;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * 抽象任务类
 * 1、task中的核心属性：任务id workId 任务执行后的结果 及对结果的异步回调
 * 2、定义 exec 抽象方法  让子类实现具体的任务
 */
public abstract class Task<R> {

    private static final AtomicInteger WORKER_ID_GENERATOR = new AtomicInteger(0);

    /**
     * 任务id
     */
    private final int taskId;

    /**
     * 任务执行结果
     */
    private R result;


    private int workerId;

    /**
     * 任务执行完后，对结果的回调
     */
    private Consumer<R> resultAction;

    public Task() {
        this.taskId = WORKER_ID_GENERATOR.getAndIncrement();
    }

    /**
     * 执行完任务后进行异步回调
     */
    void execute() {
        // 调用执行异步任务
        this.result = this.exec();

        if (resultAction != null) {
            resultAction.accept(result);
        }
        System.out.println(toString());
    }

    @Override
    public String toString() {
        return "Task{" +
                "taskId=" + taskId +
                ", workerId=" + workerId +
                ", result=" + result +
                '}';
    }


    /**
     * 留给子类重写的任务
     *
     * @return
     */
    protected abstract R exec();

    public void setWorkerId(int workerId) {
        this.workerId = workerId;
    }

    void setResultAction(Consumer<R> resultAction) {
        this.resultAction = resultAction;
    }
}
